<template>
  <el-card>
    <el-row :gutter="50" justify="start">
      <el-col :span="12">
        <el-input v-model="pageData.roleName" placeholder="请输入角色名称"></el-input>
      </el-col>
      <el-col :span="3">
        <el-button type="primary" icon="Search" @click="reload">查询</el-button></el-col
      >
    </el-row>

    <el-divider content-position="left"
      ><el-icon><DataLine /></el-icon
    ></el-divider>
    <el-row :gutter="50" justify="start">
      <el-col :span="6">
        <el-button type="primary" icon="Plus" @click="handleMethod">添加</el-button>
        <el-button type="danger" icon="Minus" @click="handleDelByIds">删除</el-button>
      </el-col>
    </el-row>

    <el-table
      height="400"
      scrollbar-always-on="true"
      :data="roleData"
      border="true"
      :default-sort="{ prop: 'admin_count', order: 'descending' }"
      style="width: 100%; margin: 20px 0px"
      @selection-change.native="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column prop="name" label="角色名称" width="180" />
      <el-table-column prop="description" label="角色描述" />
      <el-table-column prop="adminCount" label="数量" width="60" />
      <el-table-column prop="createTime" width="180" label="创建时间" />
      <el-table-column label="状态" width="80px">
        <template #default="scope">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="scope.row.status"
            @change="handleSwitch(scope.row.id)"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="180" label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleMethod(scope.row)">修改</el-button>
          <el-button size="small" type="danger" @click="handleDel(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageData.pageSize"
      v-model:page-size="pageData.pageLimit"
      :page-sizes="[10, 20, 30, 50, 100]"
      small="small"
      background="background"
      layout="prev, pager, next,->, jumper, sizes, total"
      :total="pageData.total"
      @size-change="changeSize"
      @current-change="reload"
    />
  </el-card>

  <!-- 弹出提示框动态处理功能 -->
  <el-drawer
    v-model="drawerInfo.drawer"
    :title="drawerInfo.title"
    direction="rtl"
    :before-close="handleClose"
  >
    <component
      :is="drawerInfo.componentId"
      :comData="drawerInfo.data"
      @handleCloseDailog="closeDailog"
    ></component>
  </el-drawer>

  <!-- 删除提示框  -->
  <el-dialog v-model="delDialog" title="删除确认框" width="30%" draggable>
    <div>
      <p>
        <el-icon color="red" size="20px" type="warning"><Warning /></el-icon>
        <span>确定要删除该角色吗？</span>
      </p>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="delDialog = false">取消</el-button>
        <el-button type="primary" @click="delById"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, defineAsyncComponent, computed } from "vue";
import {
  RoleVo,
  roleShowAllPage,
  RolePageVo,
  roleDelById,
  roleDelByIds,
  switchStatus,
} from "@/api/role/index";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import { WholeResult } from "../../../store/module/types/comm/pageType";

/**
 * 用于添加框的标题
 */
const roleObject = {
  addTitile: "添加角色",
  modifyTitle: "修改角色",
  addComponentId: "./AddRole.vue",
  modifyComponentId: "./ModifyRole.vue",
};

/**
 * 处理开关的状态
 */
const handleSwitch = async (id: number) => {
  let result: WholeResult = await switchStatus(id);
  ElMessage({
    type: result.code == 200 ? "success" : "error",
    message: result.mess,
  });
};

/**
 * 列表数据
 */
let roleData = ref<RoleVo[]>([]);

/**
 * 用于处理页面弹页功能
 *   使用动态组件进行动态挂载
 */
let drawerInfo = reactive({
  drawer: false,
  title: "",
  componentId: null,
  data: ref({}),
});

/**
 * 用于关闭打开的抽屉
 */
const closeDailog = () => {
  drawerInfo.drawer = false;
  reload();
};

/**
 * 处理函数，用来分别处理页面弹出框的显示和隐藏
 * @param row 行数据
 */
const handleMethod = (row) => {
  drawerInfo.drawer = true;
  if (row.id) {
    drawerInfo.title = roleObject.modifyTitle;
    drawerInfo.data = row;

    drawerInfo.componentId = defineAsyncComponent(
      () => import(`${roleObject.modifyComponentId}`)
    );
  } else {
    drawerInfo.title = roleObject.addTitile;
    drawerInfo.componentId = defineAsyncComponent(
      () => import(`${roleObject.addComponentId}`)
    );
  }
};

/**
 * 处理删除提示框的显示和隐藏
 */
const delDialog = ref(false);

/**
 * 处理删除的对象
 */
const delRow = ref();

/**
 * 处理删除的函数
 * @param row 行数据
 */
const handleDel = (row) => {
  delDialog.value = true;
  delRow.value = row;
};

/**
 * 处理删除的函数 调用后台完成删除
 */
const delById = async () => {
  let result: WholeResult = await roleDelById(delRow.value.id);
  ElMessage({
    type: result.code == 200 ? "success" : "error",
    message: result.mess,
  });
  delDialog.value = false;
  reload();
};

// 用于处理选择框的选中
let ids = [];

/**
 * 处理选择框的选中
 * @param val 选中的行数据
 */
const handleSelectionChange = (val) => {
  ids = val.map((item) => item.id);
};

/**
 * 处理删除的函数 调用后台完成删除
 */
const handleDelByIds = async () => {
  if (ids.length == 0) {
    ElMessage({
      type: "warning",
      message: "请选择要删除的数据",
    });
    return;
  } else {
    ElMessageBox.confirm("确定要删除吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      let result: WholeResult = await roleDelByIds(ids);
      ElMessage({
        type: result.code == 200 ? "success" : "error",
        message: result.mess,
      });
      reload();
    });
  }
};

/**
 * 分页以及模糊查询 ，前后交互参数
 */
const pageData = reactive({
  pageSize: 1,
  pageLimit: 10,
  roleName: "",
  total: 0,
  pages: 0,
});

/**
 * 改变每页显示的条数
 */
const changeSize = () => {
  pageData.pageSize = 1;
  reload();
};

/**
 * 调用方法 把方法数据传递给页面响应式对象
 */
const callRoleShowAllPage = async () => {
  let result: any = await roleShowAllPage(pageData);
  console.log(result, "-->");

  if (result.code == 200) {
    roleData.value = result.data.records;
    // current 后台返回的当前页数
    pageData.pageSize = result.data.current;
    // size 后台返回的每页显示的条数
    pageData.pageLimit = result.data.size;
    // total 后台返回的总条数
    pageData.total = result.data.total;
    // pages 后台返回的总页数
    pageData.pages = result.data.pages;
  }
};

/**
 * 数据表格功能
 */
const reload = () => {
  callRoleShowAllPage();
};

/**
 * 生命周期函数，表示挂载处理
 */
onMounted(() => {
  reload();
});
</script>

<style lang="scss" scoped></style>
